package own.stu.jobgib.playown.io.simple;

import org.apache.commons.lang3.time.DateFormatUtils;
import own.stu.jobgib.playown.io.common.TServer;
import own.stu.jobgib.playown.io.common.TServerSocket;
import own.stu.jobgib.playown.io.common.TSocket;

import java.io.IOException;
import java.util.Date;

public class SimpleServer extends TServer {

    public static void main(String[] args) throws Exception {
        SimpleServer server = new SimpleServer(9999);

        System.out.println(" server started .....");
        server.serve();
    }

    public SimpleServer(int port) throws Exception {
        serverSocket = new TServerSocket(port);
    }

    public void serve() {
        serverSocket.listen();

        setServing(true);

        while (!stopped_) {
            TSocket socket = null;
            try {
                socket = serverSocket.accept();
                if (socket == null) {
                    continue;
                }

                while (true) {
                    try {

                        // String s = StreamUtils.copyToString(inputStream, Charset.defaultCharset());
                        System.out.println("from client : " + socket.read());
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RuntimeException("get inputStream's data error, ", e);
                    }
                    System.out.println(" ----------- ");
                    try {
                        //StreamUtils.copy("hello ... " + new Date(), Charset.defaultCharset(), socket.getOutputStream_());
                        // socket.getOutputStream_().flush();
                        socket.write(DateFormatUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss") + " : " + "hale");
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RuntimeException("write outputStream_'s data error, ", e);
                    }
                }
            } catch (Exception e) {
                if (socket != null)
                    socket.close();
            }
        }

        setServing(false);
    }

    public void stop() {
        stopped_ = true;
        serverSocket.interrupt();
    }
}
